<?php

namespace Common\Model;
use think\Model;

class UserKuerpWarehouseLogModel extends BaseModel{

	//追加属性
    public $append = [
        'act_name',         //操作
        'add_time_text',    //添加时间
        //'supplier_name',    //供应商名称
        'wh_name',          //仓库名称
        'loc_name',         //库位名称
        'nums',             //数量
        'back_text',        //是否回滚
        'product',          //商品信息
	];

    /**
     * 库存数量
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getNumsAttr($value, $data){
		return floatval($data['nums']);
    }

    /**
     * 回滚
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getBackTextAttr($value, $data){
        $text = '';
		if($data['is_back']==1){
			$text = '<font color="red">是</font>';
		}else if($data['status']==0){
			$text = '<font color="blue">否</font>';
		}
        if(MODULE_NAME=='Api' || MODULE_NAME=='Apipad'){
            $text = strip_tags($text);
        }
		return $text;
    }


    /**
     * 商品名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getProductNameAttr($value, $data){
        $product_name = '';
        if($data['item_id']){
            $model = M('user_goods_attr');
            $wdata['id'] = $data['item_id'];
            $vo = $model->where($wdata)->find();
            $product_name = $vo['goods_name'].'-'.$vo['guige_name'].' '.$vo['color'];
        }else{
            $model = M('user_goods');
            $wdata['id'] = $data['product_id'];
            $vo = $model->where($wdata)->find();
            $product_name = $vo['goods_name'];
        }
        return $product_name;
    }

    /**
     * 商品信息
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getProductAttr($value, &$data){
        if($data['item_id']){
            $model = M('user_goods_attr');
            $wdata['id'] = $data['item_id'];
            $vo = $model->where($wdata)->find();
            $product_name = $vo['goods_name'].'-'.$vo['guige_name'].' '.$vo['color'];
        }else{
            $model = M('user_goods');
            $wdata['id'] = $data['product_id'];
            $vo = $model->where($wdata)->find();
            $product_name = $vo['goods_name'];
        }
        if(MODULE_NAME=='Api' || MODULE_NAME=='Apipad'){
            $product_name = strip_tags($product_name);
        }
        $data['product_name'] = $product_name;
        return $vo;
    }

    /**
     * 操作
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getActNameAttr($value, $data){
		$status_text = '';
		if($data['type']==1){
			$status_text = '入库';
		}else if($data['type']==2){
			$status_text = '出库';
		}
		return $status_text;
    }

    /**
     * 供应商名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getSupplierNameAttr($value, $data){
        $model = M('KuerpSuppliers');
        $wdata['id'] = $data['supplier_id'];
        $supplier_name = $model->where($wdata)->getField('supplyer_name');
		return $supplier_name;
    }

    /**
     * 仓库名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getWhNameAttr($value, $data){
        $model = M('UserKuerpWarehouse');
        $wdata['id'] = $data['wh_id'];
        $supplier_name = $model->where($wdata)->getField('name');
		return $supplier_name;
    }

    /**
     * 库位名称
     * @param $value
     * @param $data
     * @return mixed
     */
    public function getLocNameAttr($value, $data){
        $model = M('UserKuerpWarehouseLocation');
        $wdata['id'] = $data['loc_id'];
        $supplier_name = $model->where($wdata)->getField('loc_name');
		return $supplier_name;
    }

    //驳回
    function revert($kwl_vo){
        $return = [
            'status' => false,
            'errcode'   => 10000,
            'data'   => '',
            'msg'    => '失败'
        ];
        $sqls = array();
        if($kwl_vo['is_back']==1){
            $return['msg'] = '已驳回日志,无法再驳回 - 1000';
            return $return;
        }
        $kw_model = D('UserKuerpWarehouse');
        if($kwl_vo['type']==1){
            //入库单,调用出库
            $req_data = $kwl_vo;
            unset($req_data['id']);
            $req_data['type'] = 2;
            $req_data['is_back'] = 1;//不能在驳回
            $req_data['change_id'] = $kwl_vo['id'];//原始id
            $req_data['remark'] = '入库驳回：['.$kwl_vo['id'].']';
            //dump($req_data);exit;
            $res = $kw_model->out($req_data);
            if(!$res['status']){
                $return['msg'] = '驳回失败 - 1001'.$res['msg'];
                return $return;
            }
        }else{
            //出库单,调用入库
            $req_data = $kwl_vo;
            unset($req_data['id']);
            $req_data['type'] = 2;
            $req_data['is_back'] = 1;//不能在驳回
            $req_data['change_id'] = $kwl_vo['id'];//原始id
            $req_data['remark'] = '出库驳回：['.$kwl_vo['id'].']';
            //dump($req_data);exit;
            $res = $kw_model->into($req_data);
            if(!$res['status']){
                $return['msg'] = '驳回失败 - 1002 '.$res['msg'];
                return $return;
            }
        }
        $sqls = $res['sqls'];
        //状态修改
        $wdata['id'] = $kwl_vo['id'];
        $sdata['is_back'] = 1;
        $sdata['is_fq'] = 1;
        $res = $this->where($wdata)->save($sdata);
        if(!$res){
            $return['msg'] = '驳回失败 - 1003';
            return $return;
        }
        $sqls[] = M()->_sql();
        $return['sqls'] = $sqls;
        $return['status'] = true;
        $return['msg'] = '驳回成功';
        return $return;

    }
    //采购进度修改
    function cg_speed($pur_id,$pur_no,$pur_detail_id){
        $purchase_detail = M('purchase_detail');
        $purchase_order = M('purchase_order');
        $purchase = M('purchase');
        $purchase_detail_info = $purchase_detail->where(['id'=>$pur_detail_id])->find();
        $purchase_order_info = $purchase_order->where(['id'=>$pur_id])->find();
        $kd_where['is_back'] = 0;
        $kd_where['is_fq'] =0;
        $kd_where['pur_no'] = $pur_no;
        $kd_where['pur_id'] = $pur_id;
        $kd_where['pur_detail_id'] = $pur_detail_id;
        $kd_where['resource_type'] = 'purchase';
        $rk_detail_num = $this->where($kd_where)->field('SUM(CASE WHEN type = 1 THEN nums ELSE nums*(-1) END) as nums')->select();
        $rk_detail_speed = bcmul(bcdiv($rk_detail_num[0]['nums'],$purchase_detail_info['number'],2),100,0);
        $purchase_detail->where(['id'=>$pur_detail_id])->save(['rk_speed'=>$rk_detail_speed]);
        //先找出plan下所有的detail_ids
        $purchase_info = $purchase->where(['id'=>$purchase_detail_info['plan_id']])->find();
        $plan_detail_ids = $purchase_detail->where(['plan_id'=>$purchase_info['id']])
        ->field('GROUP_CONCAT(distinct(id) separator ",") as plan_detail_ids')->select();
        $kp_where['is_back'] = 0;
        $kp_where['is_fq'] =0;
        $kp_where['pur_no'] = $pur_no;
        $kp_where['pur_id'] = $pur_id;
        $kp_where['resource_type'] = 'purchase';
        $kp_where['_string'] ='FIND_IN_SET(pur_detail_id,"'.$plan_detail_ids[0]['plan_detail_ids'].'")';
        $rk_plan_num = $this->where($kp_where)->field('SUM(CASE WHEN type = 1 THEN nums ELSE nums*(-1) END) as nums')->select();
        $rk_plan_speed = bcmul(bcdiv($rk_plan_num[0]['nums'],$purchase_info['plan_number'],2),100,0);
        $purchase->where(['id'=>$purchase_detail_info['plan_id']])->save(['rk_speed'=>$rk_plan_speed]);
        //采购单入库进度
        $purchase_order_info = $purchase_order->where(['id'=>$pur_id])->find();
        $k_where['is_back'] = 0;
        $k_where['is_fq'] =0;
        $k_where['pur_no'] = $pur_no;
        $k_where['pur_id'] = $pur_id;
        $k_where['resource_type'] = 'purchase';
        $rk_all_num = $this->where($k_where)->field('SUM(CASE WHEN type = 1 THEN nums ELSE nums*(-1) END) as nums')->select();
        $rk_speed = bcmul(bcdiv($rk_all_num[0]['nums'],$purchase_order_info['number'],2),100,0);
        $purchase_order->where(['id'=>$pur_id])->save(['rk_speed'=>$rk_speed]);
    }
    //查询后置
    function _after_search(){
        $map = array();
        $request = I('request.');
        if($request['time_type']){
            $search_field = 'add_time';
            if($request['time_type']==1){
                $search_field = 'order_time';
            }else if($request['time_type']==2){
                $search_field = 'add_time';
            }
            if($request['time1'] && $request['time2']){
                $btime = strtotime($request['time1']);
                $etime = strtotime($request['time2'])+86400;
                $map['add_time'] = array('between',array($btime,$etime));
            }else if($request['time1']){
                $btime = strtotime($request['time1']);
                $map['add_time'] = array('gt',$btime);
            }else if($request['time2']){
                $etime = strtotime($request['time2'])+86400;
                $map['add_time'] = array('lt',$etime);
            }
        }
        if(I('date')){
            $dates = explode('到',I('date'));
            $btime = strtotime($dates[0]);
            $etime = strtotime($dates[1])+86400-1;
            $map['add_time'] = array('between',array($btime,$etime));
        }
        if($request['product_id']){
            $map['product_id'] = array('in',$request['product_id']);
        }
        if($request['supplier_id']){
            $map['wpde.resource'] = 'Supplier';
            $map['wpde.resource_id'] = $request['supplier_id'];
        }
        return $map;
    }

    //独立列表,做了分页
    public function _list($model, $map, $listRows='' ,$sortBy ='' , $field='*') {
        $model = $model ? $model : M($this->model_name);
        $request = I('request.');
        //排序字段 默认为主键名
        if($sortBy){
            //自定义
            $order = $sortBy;
        }else{
            $order = $this->getOrder($model);
        }
        //取得满足条件的记录数
        $count = $model->where($map)->count();
        //echo M()->_sql();exit;
        if (!empty($request ['listRows'])) {
            $listRows = $request ['listRows'];
        }else if(!$listRows){
            $listRows = C('listRows') ? C('listRows') : 20;
        }
		$listRows = $listRows>500 ? 500 : $listRows;
        $page_count = ceil($count / $listRows);
        if ($count > 0) {
            //创建分页对象
            $p = new \Think\AdminPage($count, $listRows);
            //分页查询数据
            $voList = $model->field($field)->where($map)->order($order)->limit($p->firstRow . ',' . $p->listRows)->select();
            //$voList = $model->field($field)->where($map)->order($order)->select();
            //echo M()->_sql();exit;
            //分页跳转的时候保证查询条件
            foreach ($map as $map_key => $map_val) {
                if (!is_array($map_val)) {
                    $p->parameter .= "$map_key=" . urlencode($map_val) . "&";
                }
            }
			//zzy 属性追加 2019/11/20
			if (!empty($this->append)) {
				if($this->append_ext){
					$this->append = array_merge($this->append,$this->append_ext);
				}
				foreach($voList as &$vo){
					foreach ($this->append as $key => $name) {
						// 检测属性获取器
						$method = 'get' . $this->camelize($name) . 'Attr';
						$value = $vo[$name] ? $vo[$name] : null;
						if (method_exists($this, $method)) {
							$value = $this->$method($value, $vo);
							$vo[$name] = $value;
						}
					}
				}
			}
			//zzy 属性隐藏 2019/12/6
			if (!empty($this->hidden)) {
				foreach($voList as &$vo){
					foreach($vo as $field=>$val){
						if(in_array($field,$this->hidden)){
							unset($vo[$field]);
						}
					}
				}
			}
            //分页显示
            $page = $p->show();

            //列表排序显示
            $sortImg = $sort; //排序图标
            $sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
            $sort = $sort == 'desc' ? 1 : 0; //排序方式
        }else{
			$p = new \Think\AdminPage($count, $listRows);
			$voList = '';
			$page = $p->show();
		}

        $data['list'] = $voList;
        if(MODULE_NAME!='Api'){
			Cookie('_currentUrl_', __SELF__);
			$data['page'] = $page;
		}
        //$data['map'] = $map;
		$data['page_count'] = $p->totalPages;//总页数
		$data['count'] = $p->totalRows;//总条数
        $data['listRows'] = $p->listRows;//总条数
		$data['now_page'] = $p->nowPage;
        return $data;
    }

 


}